import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:xin_he/page/shopping_car/xin_he_goods_payment/xin_he_payment_methods_model.dart';
import 'package:xin_he/utils/xin_he_UI_constancs.dart';

import '../../../routes/xin_he_routes.dart';
import '../../../service/xin_he_reqest.dart';
import '../../../utils/xin_he_event_bus.dart';
import '../../../utils/xin_he_storage.dart';
import '../../../utils/xin_he_toast.dart';
import '../../mine/xin_he_adress_management/model/xin_he_address_item_model_entity.dart';
import '../../mine/xin_he_mine_work_space/xin_he_my_studio_entity.dart';
import '../xin_he_instant_pay/xin_he_instant_pay_view.dart';
import '../xin_he_shopping_car/xin_he_shop_cart_goods_entity.dart';
import 'xin_he_goods_payment_state.dart';

class XinHeGoodsPaymentLogic extends GetxController {
  final XinHeGoodsPaymentState state = XinHeGoodsPaymentState();

  List iconList = ['pay_method_alipay','pay_method_wechat','pay_method_redbag_small','pay_method_shopping','pay_method_mengya','pay_method_oil'];
  List titleList = ['余额','微信支付','消费金红包','购物金','未解冻云茶籽','茶油卡'];
  RxInt selectedIndex = 0.obs;
  RxList payMethodsList = [XinHePaymentMethodModel(),XinHePaymentMethodModel(),XinHePaymentMethodModel(),XinHePaymentMethodModel(),XinHePaymentMethodModel(),XinHePaymentMethodModel()].obs;

  RxString addressStr = '请选择地址'.obs;
  Rx<XinHeAddressItemModelEntity> addressModel = XinHeAddressItemModelEntity().obs;

  RxList goodsList = [].obs;
  RxDouble totalAmount = 0.00.obs;
  RxInt totalCount = 0.obs;

  RxDouble goodsHeight = 0.00.obs;
  Rx<XinHeMyStudioEntity> studioModel = XinHeMyStudioEntity().obs;

  RxString addressName = '芯禾深服宝安门店'.obs;
  RxString remark = ''.obs;

  RxList totalOrderItems = [].obs;

  Map shopMap = {};
  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();

    var arg = Get.arguments;
    var list = [];
    if(arg != null) {
      goodsList.value =  arg['list'];
      totalAmount.value = arg['totalAmount'];
      totalCount.value = arg['count'];
    }



    int section = 0;
    int items = 0;

    List orderItemsList = [];
    for(XinHeShopCartGoodsEntity e in  goodsList.value) {
      section++;
      List<XinHeShopCartGoodsOrderItems> item = [];
      for(XinHeShopCartGoodsOrderItems el in e.orderItems!) {
        if(el.isSelected) {
          item.add(el);
          items ++;
          orderItemsList.add(el);
        }
      }
    }


    goodsHeight.value = section*44+items*120;

    List orderParamList = [];
    for(XinHeShopCartGoodsOrderItems e in orderItemsList) {
      Map map = {
        'orderItemId': e.orderItemId??0,
        'sellerUserId': e.goodsSellerUserId??0
      };
      orderParamList.add(map);
    }

    totalOrderItems.value = orderParamList;

    bus.on(XinHeStorage.settingDefaultAddress, (arg) async {
      await requestDefaultAddress();

      tabSelectedIndex(state.tabIndex.value);
    });

    ///门店地址
    requestStudioData();

    //查询默认地址
    requestDefaultAddress();
  }


  List copyWithList(List list) {
    List copyList = [];
    for (var item in list) {
      if (item is Map) {
        copyList.add(Map.from(item));
      } else if (item is List) {
        copyList.add(copyWithList(item));
      } else {
        copyList.add(item);
      }
    }
    return copyList;
  }

    @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
  }


  ///默认地址
  requestDefaultAddress() async {
    var userId = await XinHeLocalStorage.get(XinHeStorage.userId);
    Map<String,dynamic> param = {
      'userId': userId
    };
    XinHeRequestDataResult result = await XinHeHttpRequestData.requestUniversalPost(url: '/address/findDefaultAddress',params: param,isPost: false);

    if(!result.result){
      XinHeToast.center(result.data['message']);
      return ;
    }

    XinHeAddressItemModelEntity model = XinHeAddressItemModelEntity.fromJson(result.data['data']);
    addressModel.value = model;
  }



  tabSelectedIndex(int index) {
    state.tabIndex.value = index;
    if(index == 0) {
      addressName.value = shopMap['name'];
      addressStr.value = shopMap['address'];
    }else {
      addressName.value = '${addressModel.value.name!}  ${addressModel.value.telephone!}' ;
      addressStr.value =  addressModel.value.province!+ addressModel.value.city!+ addressModel.value.area!+addressModel.value.detail!;
    }
  }

  commitOrder() async{

    var userId = await XinHeLocalStorage.get(XinHeStorage.userId);
    Map<String,dynamic> param = {
    'userId': userId,
     'addressId': state.tabIndex.value == 0 ? 0: addressModel.value.id,
     'shopId': state.tabIndex.value == 0 ? shopMap['id']:0,
     'type':'COMMON',
     'distributionType': state.tabIndex.value == 0 ?  'ONESELF_TAKE': 'MAIL',
      'remark': remark.value,
      'sellerOrderList': totalOrderItems.value
    };
    XinHeRequestDataResult result = await XinHeHttpRequestData.requestUniversalPost(url: '/order/saveOrderByShopCart',params: param,isPost: true);

    if(!result.result){
    XinHeToast.center(result.data['message']);
    return ;
    }

    bus.emit(XinHeStorage.refreshCart);

    if(result.data['code'] == 0 ){
      Get.bottomSheet(
        XinHeInstantPayPage(
          zoneType: 1,
          totalPrice: double.parse(getActualAmount()),
          count: totalCount.value,
          order: result.data['data'],
          scene: PayScene.fromGoodsCartOrder,
        )
        ,persistent: false,isScrollControlled: true,);
    }else {
      XinHeToast.center(result.data['message']);

    }


    // Get.offNamed(XinHeRoutes.paySuccess);


  }

  requestStudioData()async{

    XinHeRequestDataResult result = await XinHeHttpRequestData.requestUniversalPost(url: '/shop/queryShop',isPost: false);

    if(!result.result){
      XinHeToast.center(result.data['message']);
      return ;
    }

    shopMap = result.data['data'];
    // XinHeMyStudioEntity odel = XinHeMyStudioEntity.fromJson(result.data['data']);
    // studioModel.value = odel;

    addressName.value = shopMap['name'];
    addressStr.value = shopMap['address'];

  }
  getActualAmount() {
    var expressFee = state.tabIndex.value == 0 ? 0.0: 10.0;
    var amount =  totalAmount.value + expressFee;
    return '$amount';
  }


}
